#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h> // libpq头文件

void printUserList(PGconn *conn) {
    PGresult *res = PQexec(conn, "\\du");

    if (PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr, "Query execution failed: %s", PQerrorMessage(conn));
        PQclear(res);
        PQfinish(conn);
        exit(1);
    }

    int numRows = PQntuples(res);

    printf("User list:\n");

    for (int i = 0; i < numRows; ++i) {
        printf("%s\n", PQgetvalue(res, i, 0));
    }

    PQclear(res);
}

int main() {
    const char *conninfo = getenv("MYDB_CONN_INFO"); // 从环境变量中获取数据库连接信息

    if (!conninfo) {
        fprintf(stderr, "Database connection information not found in environment variable MYDB_CONN_INFO\n");
        exit(1);
    }

    PGconn *conn = PQconnectdb(conninfo);

    if (PQstatus(conn) != CONNECTION_OK) {
        fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn));
        PQfinish(conn);
        exit(1);
    }

    printUserList(conn);

    PQfinish(conn);

    return 0;
}
